package com.chu.cloud.service.impl;

import com.chu.cloud.entity.mongo.AuthAccessToken;
import com.chu.cloud.repository.AuthAccessTokenDao;
import com.chu.cloud.util.DateUtils;
import com.chu.cloud.util.JsonUtils;
import com.chu.cloud.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Date;

/**
 * @author: Tianshu.CHU
 * @Date: 2018/3/28 10:22
 * @Description:
 */
@Service
@Slf4j
public class AuthAccessTokenService {

    @Autowired
    private StrUtil strUtil;

    @Autowired
    private AuthAccessTokenDao accessTokenDao;

    /**
     * @param id 用户id
     * @param username 用户名
     * @param mobile 用户手机
     * @param ip 用户ip
     * @return 为用户创建登录token
     */
    public AuthAccessToken saveToken(Integer id,String username,String mobile,String ip){
        Assert.notNull(id,"用户id不能为空");
        Assert.notNull(username,"用户名不能为空");
        Assert.notNull(mobile,"用户手机不能为空");

        AuthAccessToken accessToken = new AuthAccessToken();

        accessToken.setUserId(id);
        accessToken.setUserName(username);
        accessToken.setMobile(mobile);
        accessToken.setBindIp(ip);
        accessToken.setToken(strUtil.generateToken());
        accessToken.setStatus(true);
        //30天有效
        accessToken.setExpireTime(DateUtils.dayOffset(new Date(),30));
        accessToken.setCreateAt(new Date());

        AuthAccessToken authAccessToken = accessTokenDao.save(accessToken);

        log.info("保存Mongodb token成功:"+ JsonUtils.obj2json(accessToken));
        return authAccessToken;

    }

    public AuthAccessToken findToken(String token){

        return accessTokenDao.findByToken(token);
    }

}
